package com.ruoyi.web.controller.tool;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/alipay")
public class AlipayController {
    static {
        //设置支付宝的配置信息
        Config config = new Config();
        //  设置请求使用的支付宝网关
        config.protocol = "https";
        config.gatewayHost = "openapi-sandbox.dl.alipaydev.com";
        // 设置应用私钥
        config.merchantPrivateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCqRU8FQ2ravy9aLHYydJxd77ZXiGep3tvPqSECAz093IFwoJOFxr9txTrFbAFyLKocFNfpNUbXaQwNvfTFGXavQ8lHeK7ZV19t5bxbg6PGWbdZM+SZvK1DqFS+T2y9PjG1gDczfzsp65iNqzg21cmigMTg07p80rrFnlyMvA5u6Gpf6sWCa6nyrO1vcxASOk66lMjpYQP29/yyeBp4b955KPdx5BybnpCNwrBBgLHDhfru6h+oQUSow/OnV3obrBB6pCGtXy9YXWIrxklAsOLzMVUM7RJzK3FgPgXQ3Ex5IfDfitGVPbtw66FJDuOJ2BFyHOUgj1phWbTTXV+iJfGRAgMBAAECggEAKWkv3cTWwRrMZm731C+eNA5v13waUiscZLXqjDXDeD8f0AeNuXRr7EOSlp88/sq0GJ5NIK/PaeZngxQW6rTVs6yV0Gceh0eDsxOzqsIqW7xIJk7Do0xLC3BuI9bnSGNO7aigREsGVZyx/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//设置支付宝公钥
        config.alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiFFM9F0kof+fEX4STc/psrdsxqs6QaIbIizNWIrrNdJezExHy6tkhlsVB/K1ipmkAu2qK76udrPKOH+Uqor6sv4iedbKEmDdMPAogDfonIEapEDp8vel18Ib7+fjoq63eyPpJBxN7yudYW504tHGbTkRe/AZyBSt2043jKiNIayIO0MLaL7f/hWx6c28rP7tUouChqPElIbLFl73h64Xodi+cmYMcajLiW5+GzR/zvLkmu5AOZ0EufX4gYoLBqxjKN7ZKbaPOY83a2XEWAJo0Ol8YQcrAFewAhi+rl5e9JFQ8wUvNiXDPhBP/UfbwHit8ggd0sAjM3AGP6zbSm18qQIDAQAB";
        //设置签名方式
        config.signType = "RSA2";
        //设置应用ID
        config.appId = "2021000148659975";

        //支付宝回调notifyUrl
// config.notifyUrl="http://localhost:8080/alipay/notify";
//内网穿透
        config.notifyUrl="http://x9458c68.natappfree.cc/alipay/notify";

        Factory.setOptions(config);
    }

    //获取订单的支付二维码的接口
    @GetMapping("/pay")
    public void pay( HttpServletResponse servletResponse, String subject, String outTradeNo,Integer totalAmount)
            throws Exception {
        System.out.println(subject+" "+outTradeNo+" "+totalAmount);

//支付宝回调notifyUrl
// config.notifyUrl="";
        //发起调用支付宝接口
        AlipayTradePrecreateResponse response =
                Factory.Payment.FaceToFace().preCreate(subject, outTradeNo, totalAmount+"");
//响应解析
        String httpBody = response.getHttpBody();
        System.out.println("响应结果：");
        System.out.println(httpBody);
//获取二维码信息
        JSONObject jsonObject = JSONUtil.parseObj(httpBody);
        String qrUrl =
                jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();
//生成二维码
// 生成指定url对应的二维码到文件，宽和高都是300像素
// QrCodeUtil.generate(qrUrl, 300, 300, FileUtil.file("d:/qrcode.jpg"));
//设置响应servletResponse
        ServletOutputStream out = servletResponse.getOutputStream();
        QrCodeUtil.generate(qrUrl, 300, 300,"",out);
        out.close();
    }

    //扫码支付完成，支付宝回调我们的接口
    @PostMapping("/notify")
    public String notifyUrl(HttpServletRequest request){
        System.out.println("回调。。。。。。");
// 获取支付结果
// 根据结果进行业务处理：修改订单的状态
        String outTradeNo = request.getParameter("out_trade_no");
        String trade_status = request.getParameter("trade_status");
        System.out.println(outTradeNo);
        System.out.println(trade_status);
        if ("TRADE_SUCCESS".equals(trade_status)){
            System.out.println("支付成功");
        }
        return outTradeNo;
    }

    //查询支付结果的接口
    @GetMapping("/queryPay")
    public String queryPay(String outTradeNo) throws Exception {
        // 查询支付结果
        AlipayTradeQueryResponse queryResponse =
                Factory.Payment.Common().query(outTradeNo);
        String httpBody = queryResponse.getHttpBody();
        System.out.println(httpBody);
//解析支付结果
        JSONObject jsonObject = JSONUtil.parseObj(httpBody);
        String trade_status =
                jsonObject.getJSONObject("alipay_trade_query_response").get("trade_status").toString();
        return trade_status;
    }

    @GetMapping("/back")
    public String back(String outTradeNo,Integer refundAmount) throws Exception {
        //2、调用支付宝接口：退款
        AlipayTradeRefundResponse response = Factory.Payment.Common().refund(outTradeNo, refundAmount+"");
        //3、响应解析
        String httpBody = response.getHttpBody();
        System.out.println("响应结果：");
        System.out.println(httpBody);

        return "退款成功";
    }
}
